Ext.ns('sink', 'demos', 'Ext.ux', 'Ext.plugin.touch.form');

Ext.ux.UniversalUI = Ext.extend(Ext.Panel, {
    fullscreen: true,
    layout: 'card',
    //items: [ demos.Login ],
    //  {
    //cls: 'launchscreen',
    //id: 'launchscreen',
    //html: '<div><img src="resources/img/sencha.png" width="210" height="291" /><h1>Welcome to Sencha Touch</h1><p>This is a comprehensive collection of our examples in an <br /> easy-to-navigate format. Each sample has a â€œview sourceâ€ button which dynamically displays its associated code.<br /><br /><span>Sencha Touch (' + Ext.version +')</span></p></div>'
    //}
    backText: 'Back',
    saveText: 'Save',
    useTitleAsBackText: true,
    initComponent : function() {
        this.navigationButton = new Ext.Button({
            hidden: true, // KR removed Ext.is.Phone || Ext.Viewport.orientation == 'landscape' -->  false
            text: Ext.is.Phone ? 'Nav' : 'Navigation',
            handler: this.onNavButtonTap,
            scope: this
        });
        
        this.backButton = new Ext.Button({
            text: this.backText,
            ui: 'back',
            handler: this.onUiBack,
            hidden: true,
            scope: this
        });
        
        this.saveButton = new Ext.Button({
            text: this.saveText,
            ui: 'confirm',
            width: '80',
            handler: this.onSave,
            hidden: true,
            scope: this
        });
        
        this.addHxButton = new Ext.Button({
            iconCls: 'iconHx_add',
            iconMask: true,
            ui: 'plain',
            handler: this.onAddHx,
            hidden: true,
            scope: this
        });
        
        this.addMxButton = new Ext.Button({
            iconCls: 'add',
            iconMask: true,
            ui: 'plain',
            handler: this.onAddMx,
            hidden: true,
            scope: this
        });
        
        var btns = [this.navigationButton];
        
        if (Ext.is.Phone) {
            btns.unshift(this.backButton);
        }

        this.navigationBar = new Ext.Toolbar({
            dock: 'top',
            defaults: {
                iconMask: true,
                ui: 'dark'
//                ui: 'plain'
            },
//            scroll: {
//                direction: 'horizontal',
//                useIndicators: false
//            },
            title: this.title,
            items: btns.concat(this.buttons || [])
        });

        this.navigationPanel = new Ext.NestedList({
            store: sink.StructureStore,
            useToolbar: true, // KR removed Ext.is.Phone ? false : true,
            updateTitleText: false,
            dock: 'left',
            hidden: true, // KR removed !Ext.is.Phone && Ext.Viewport.orientation == 'portrait',
            toolbar: null, // KR removed Ext.is.Phone ? this.navigationBar : null,
            listeners: {
                itemtap: this.onNavPanelItemTap,
                scope: this
            }
        });

        this.navigationPanel.on('back', this.onNavBack, this);

        if (1 == 1) { // KR removed !Ext.is.Phone
            this.navigationPanel.setWidth(250);
        }

        this.dockedItems = this.dockedItems || [];
        this.dockedItems.unshift(this.navigationBar);

        if (1 == 2) { // KR removed !Ext.is.Phone && Ext.Viewport.orientation == 'landscape'
            this.dockedItems.unshift(this.navigationPanel);
        }
        else if (1 == 2) { // KR removed Ext.is.Phone
            this.items = this.items || [];
            this.items.unshift(this.navigationPanel);
        }

        this.addEvents('navigate');


        Ext.ux.UniversalUI.superclass.initComponent.call(this);
    },

    toggleUiBackButton: function() {
        var navPnl = this.navigationPanel;

        if (1 == 2) { // KR removed Ext.is.Phone
            if (this.getActiveItem() === navPnl) {

                var currList      = navPnl.getActiveItem(),
                    currIdx       = navPnl.items.indexOf(currList),
                    recordNode    = currList.recordNode,
                    title         = navPnl.renderTitleText(recordNode),
                    parentNode    = recordNode ? recordNode.parentNode : null,
                    backTxt       = (parentNode && !parentNode.isRoot) ? navPnl.renderTitleText(parentNode) : this.title || '',
                    activeItem;


                if (currIdx <= 0) {
                    this.navigationBar.setTitle(this.title || '');
                    this.backButton.hide();
                } else {
                    this.navigationBar.setTitle(title);
                    if (this.useTitleAsBackText) {
                        this.backButton.setText(backTxt);
                    }

                    this.backButton.show();
                }
            // on a demo
            } else {
                activeItem = navPnl.getActiveItem();
                recordNode = activeItem.recordNode;
                backTxt    = (recordNode && !recordNode.isRoot) ? navPnl.renderTitleText(recordNode) : this.title || '';

                if (this.useTitleAsBackText) {
                    this.backButton.setText(backTxt);
                }
                this.backButton.show();
            }
            this.navigationBar.doLayout();
        }

    },

    onUiBack: function() {
        var navPnl = this.navigationPanel;

        // if we already in the nested list
        if (this.getActiveItem() === navPnl) {
            navPnl.onBackTap();
        // we were on a demo, slide back into
        // navigation
        } else {
            this.setActiveItem(navPnl, {
                type: 'slide',
                reverse: true
            });
        }
        this.toggleUiBackButton();
        this.fireEvent('navigate', this, {});
    },

    onSave: function() {
    //    if (Ext.is.Phone) demos.Tabcontrol.tabBar.setVisible(true);

//        demos.Examcontrol.tabBar.activeTab = demos.CCHPI;
//        demos.Examcontrol.tabBar.currentCard = demos.CCHPI;
        var ui = sink.Main.ui;
        var navBar = ui.navigationBar;

        this.setActiveItem(demos.Maincontrol, {type: 'slide', direction: 'right'});
        this.currentCard = demos.Maincontrol;

        this.addHxButton.hide();
        this.addMxButton.hide();
        this.saveButton.hide();
        
        navBar.titleEl.dom.innerText = 'DLC EMR';

        this.navigationBar.doComponentLayout();
        
        this.fireEvent('navigate', this, {});
    },

    onAddHx: function() {
    	
    	var cchpicard = Ext.getCmp('cchpi');
    	var hpicount = cchpicard.items.items.length;
    	var hpinew = new demos.HPIpanel({
	    		id: 'hpi'+hpicount,
	    		name: 'hpi'+hpicount,
	    		idcount: hpicount,
	    	});
  
    	cchpicard.items.items.push(hpinew);
    	cchpicard.hpicount = hpicount;
    	cchpicard.doLayout();  // This is necessary to add El to panel
//    	cchpicard.doComponentLayout();
//    	cchpicard.update;
    	
    	console.debug('HPIitems='+cchpicard.items.items.length)
    	
    	//    if (Ext.is.Phone) demos.Tabcontrol.tabBar.setVisible(true);

//            demos.CCHPI.items;

//            this.navigationBar.doComponentLayout();
            
//            this.fireEvent('navigate', this, {});
        },

        onAddMx: function() {
        	
        	var mdmcard = Ext.getCmp('mdm');
        	var mdmcount = mdmcard.items.items.length;
        	var mdmnew = new demos.MDMpanel({
    	    		id: 'mdm'+mdmcount,
    	    		name: 'mdm'+mdmcount,
    	    		idcount: mdmcount,
    	    		MDMtitle: [{
    	    	        id: 'mdm'+mdmcount,
    	    	        name: 'mdm'+mdmcount,
    	    	    }],
    	    	});
      
        	mdmcard.items.items.push(mdmnew);
        	mdmcard.mdmcount = mdmcount;
        	mdmcard.update;
        	mdmcard.doLayout();  // This is necessary to add El to panel
//        	cchpicard.doComponentLayout();
//        	cchpicard.update; 
        	
        	console.debug('MDMitems='+mdmcard.items.items.length)
        	
        	//    if (Ext.is.Phone) demos.Tabcontrol.tabBar.setVisible(true);

//                demos.CCHPI.items;

//                this.navigationBar.doComponentLayout();
                
//                this.fireEvent('navigate', this, {});
        },
        
        onNavPanelItemTap: function(subList, subIdx, el, e) {
        var store      = subList.getStore(),
            record     = store.getAt(subIdx),
            recordNode = record.node,
            nestedList = this.navigationPanel,
            title      = nestedList.renderTitleText(recordNode),
            card, preventHide, anim;

        if (record) {
            card        = record.get('card');
            anim        = record.get('cardSwitchAnimation');
            preventHide = record.get('preventHide');
        }

        if (!recordNode.childNodes.length && !preventHide) { // KR removed (Ext.Viewport.orientation == 'portrait' && !Ext.is.Phone && !recordNode.childNodes.length && !preventHide)
        	this.addHxButton.hide();			// remove Exam back button because unnecessary when changing Nav
        	this.addMxButton.hide();			// remove Exam back button because unnecessary when changing Nav
        	this.saveButton.hide();			// remove Exam back button because unnecessary when changing Nav
        	this.navigationPanel.hide();
        }

        if (card) {
            this.setActiveItem(card, anim || 'slide');
            this.currentCard = card;
        }

        if (title) {
            this.navigationBar.setTitle(title);
        }
        this.toggleUiBackButton();
        this.fireEvent('navigate', this, record);
    },

    onNavButtonTap : function() {
        this.navigationPanel.showBy(this.navigationButton, 'fade');
    },

    layoutOrientation : function(orientation, w, h) {
	//	Ext.Msg.alert('Rotate', 'Device has been rotated', Ext.emptyFn); //  --> used for debugging rotation            		
        if (1 == 1) {  // KR removed (!Ext.is.Phone)
            if (1 == 1) { // KR removed (orientation == 'portrait')
                this.navigationPanel.hide(false);
                this.removeDocked(this.navigationPanel, false);
                if (this.navigationPanel.rendered) {
                    this.navigationPanel.el.appendTo(document.body);
                }
                this.navigationPanel.setFloating(true);
                this.navigationPanel.setHeight(400);
                if (Ext.is.Phone) {
                	if (orientation == 'landscape') {
                		this.navigationButton.setText('Navigation')
                	} else {
                		this.navigationButton.setText('Nav')                		
                	}
                	
                }
//                this.navigationButton.hide(); // KR changed .show(false) --> removed as not necessary
            }
            else {
                this.navigationPanel.setFloating(false);
                this.navigationPanel.show(false);
                this.navigationButton.hide(true); // KR changed from false to true
                this.insertDocked(0, this.navigationPanel);
            }
            this.navigationBar.doComponentLayout();
        }
        
        this.doComponentLayout();
        this.doLayout();
        
        Ext.ux.UniversalUI.superclass.layoutOrientation.call(this, orientation, w, h);
    }
});

sink.Main = {
    init : function() {
        this.sourceButton = new Ext.Button({
            text: 'Source',
            ui: 'action',
            hidden: true,
            handler: this.onSourceButtonTap,
            scope: this
        });

        this.codeBox = new Ext.ux.CodeBox({scroll: false});

        var sourceConfig = {
            items: [this.codeBox],
            bodyCls: 'ux-code',
            scroll: {
                direction: 'both',
                eventTarget: 'parent'
            }
        };

        if (!Ext.is.Phone) {
            Ext.apply(sourceConfig, {
                width: 500,
                height: 500,
                floating: true
            });
        }

        this.sourcePanel = new Ext.Panel(sourceConfig);

        this.ui = new Ext.ux.UniversalUI({
            title: Ext.is.Phone ? 'DLC EMR' : 'DLC EMR',  //'Docujot' : 'Docujot EMR',
            useTitleAsBackText: false,
            navigationItems: sink.Structure,
            buttons: [{xtype: 'spacer'}, this.sourceButton],
            listeners: {
                navigate : this.onNavigate,
                scope: this
            }
        });
        
        this.ui.setActiveItem(demos.Login, 'slide');
        this.ui.currentCard = demos.Login;

        this.onlinestore.addListener('load', function () {
            console.log("I think we are online");
            sink.Main.offlinestore.proxy.clear();
            this.each(function (record) {
            	i = sink.Main.offlinestore.data.items.length;
            	ListStoredata = demos.ListStore.data.items[i]
            	patname = ListStoredata.data.lastName+', '+ListStoredata.data.firstName;
                record.data.name = patname;
                var photo = sink.Main.offlinestore.add(record.data)[0];
                photo.setUrl();
                console.log(name+'::'+url);
            });
            sink.Main.offlinestore.sync();
            demos.Patientslist.bindStore(sink.Main.offlinestore);
        });
    
        this.onlinestore.load();
    },

    setPhotoUrl: function (id, dataUrl) {
        var photo = this.offlinestore.getById(id);
        photo.set('url', dataUrl);
        this.offlinestore.sync();
    },

    onNavigate : function(ui, record) {
        if (record.data && record.data.source) {
            var source = record.get('source');
            if (this.sourceButton.hidden) {
                this.sourceButton.show();
                ui.navigationBar.doComponentLayout();
            }

            Ext.Ajax.request({
                url: source,
                success: function(response) {
                    this.codeBox.setValue(Ext.htmlEncode(response.responseText));
                },
                scope: this
            });
        }
        else {
            this.codeBox.setValue('No source for this example.');
            this.sourceButton.hide();
            this.sourceActive = false;
            this.sourceButton.setText('Source');
            ui.navigationBar.doComponentLayout();
        }
    },

    onSourceButtonTap : function() {
        if (!Ext.is.Phone) {
            this.sourcePanel.showBy(this.sourceButton.el, 'fade');
        }
        else {
            if (this.sourceActive) {
                this.ui.setActiveItem(this.ui.currentCard, Ext.is.Android ? false : 'flip');
                this.sourceActive = false;
                this.ui.navigationBar.setTitle(this.currentTitle);
                this.sourceButton.setText('Source');
            }
            else {
                this.ui.setActiveItem(this.sourcePanel, Ext.is.Android ? false : 'flip');
                this.sourceActive = true;
                this.currentTitle = this.ui.navigationBar.title;
                this.ui.navigationBar.setTitle('Source');
                this.sourceButton.setText('Example');
            }
            this.ui.navigationBar.doLayout();
        }
        
        this.sourcePanel.scroller.scrollTo({x: 0, y: 0});
    }
};

Ext.setup({
    tabletStartupScreen: 'resources/img/tablet_startup.png',
    phoneStartupScreen: 'resources/img/phone_startup.png',
    icon: 'resources/img/icon.png',
    glossOnIcon: false,

    onReady: function() {
        sink.Main.init();
    }
});

Ext.ns('demos', 'demos.Data');